using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using VisualStudioSensor;
using TeamFoundationServerSensor;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using System.Net;

/// <summary>
/// Summary description for Global
/// </summary>
public partial class Global : System.Web.HttpApplication {

    /// <summary>
    /// Constructor for global application initialization.
    /// </summary>
    public Global() {
    }

    /// <summary>
    /// Routines that get run on server start. Order matters.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Application_Start(object sender, EventArgs e) {

        // Start the logger.
        Logger.TheInstance.Initialize(this.Server.MapPath("~/Logs/log_"
            + DateTime.Today.ToShortDateString().Replace('/', '_') + ".txt"));

        // Start settings.
        string settingpath = this.Server.MapPath("~/settings.ini");
        if (Settings.Instance.loadFile(settingpath)) {
            Logger.TheInstance.Log("Loaded setting file correctly from: " + settingpath, LogLevel.Info);
        }
        else {
            Logger.TheInstance.Log("Could not load setting file. Using defaults. ", LogLevel.Warning);
        }

        // Start stuff
        start();
    }

    /// <summary>
    /// Should only occur when the application is shutting down.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Application_End(object sender, EventArgs e) {

        Logger.TheInstance.Log("Server is shutting down.", LogLevel.Info);
        Logger.TheInstance.Log("Attempting to stop the sensorshell.", LogLevel.Info);

        Settings.Instance.save();
        stop("Application Ender");
    }

    void Application_Error(object sender, EventArgs e) {
        // Code that runs when anunhandled error occurs

        Logger.TheInstance.Log(Server.GetLastError());
    }

    void Session_Start(object sender, EventArgs e) {
        // Code that runs when a new session is started
    }

    void Session_End(object sender, EventArgs e) {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
    }

    /// <summary>
    /// Used to shutdown the SensorShell.
    /// </summary>
    /// <param name="caller">IDentifier of the calling function.</param>
    public static void stop(string caller) {
        Logger.TheInstance.Log("Sensor Shutdown Attempt by '" + caller + "'", LogLevel.Info);
        SensorShellProxy.TheInstance.Stop(int.Parse(Settings.Instance.getSetting("QuitTimeout")));
        Settings.Instance.save();
        Logger.TheInstance.Log("Sensorshell Offline", LogLevel.Info);
    }

    /// <summary>
    /// Use to startup the server.
    /// </summary>
    public static void start() {

        // Attempt to open a connection to the Hackystat server.
        SensorShellControl shellControl =
            new SensorShellControl("VisualStudioTeamFoundationServer", Settings.Instance.getSetting("SensorPath"));
        if (!shellControl.Connect()) {
            Logger.TheInstance.Log("Could not start sensorshell service, data will be lost.", LogLevel.Error);
        }
        else {
            Logger.TheInstance.Log("Sensorshell Online", LogLevel.Info);
        }
    }
}
